﻿using System.ServiceProcess;
using System.Timers;
using System.Configuration;
using System;
using Fujitsu.JiraAnalysis.Common;
using Fujitsu.JiraAnalysis.DAL;

namespace Fujitsu.JiraAnalysis.ReplicationService
{
    public partial class ReplicationService : ServiceBase
    {
        private Timer timer;
        private int TimerInterval { get; set; }

        private ProjectStorage projectStorage = new ProjectStorage();
        private CommandDispatcher syncDispatcher = new CommandDispatcher();

        public ReplicationService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            InitializeTimer();
            timer.Start();
        }

        protected override void OnStop()
        {
            timer.Stop();
        }

        private void InitializeTimer()
        {
            try
            {
                var timerIntervalString = ConfigurationManager.AppSettings["UpdatePeriod"];
                if (string.IsNullOrEmpty(timerIntervalString))
                    throw new InvalidOperationException();
                TimerInterval = int.Parse(timerIntervalString);
            }
            catch (InvalidOperationException ex)
            {
                EventLogger.CreateInstance(new EventLogWrapper()).LogWriteError(string.Format("'UpdatePeriod' can't be found in App.config . Using default: 10 sec interval.\n {0}", ex.Message));
                TimerInterval = 10000;
            }
            catch (FormatException ex)
            {
                EventLogger.CreateInstance(new EventLogWrapper()).LogWriteError(string.Format("Couldn't parse 'UpdatePeriod'. Using default: 10 sec interval.\n {0}", ex.Message));
                TimerInterval = 10000;
            }
            timer = new Timer(TimerInterval);
            timer.Elapsed += timer_Elapsed;
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var projects = projectStorage.GetProjectsToSynchronize();

            foreach (var project in projects)
            {
                var command = new SyncCommand(project);
                syncDispatcher.ExecuteCommand(command);
            }
        }
    }
}
